﻿using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Collections.Generic;
using TSharp.Core.Util;
using System;
using TSharp.Core;

namespace RouteDebug
{
    public class RouteDebuggerHttpModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.EndRequest += OnEndRequest;
            context.BeginRequest += new System.EventHandler(context_BeginRequest);
            initExclude(context);
        }

        void context_BeginRequest(object sender, System.EventArgs e)
        {
            if (RouteTable.Routes.Count == 0 || RouteTable.Routes.Last() != DebugRoute.Singleton)
            {
                RouteTable.Routes.Add(DebugRoute.Singleton);
            }
        }

        private HashSet<string> resourceExtensions = new HashSet<string>(
            new CommonEqualityComparer<string>((x, y) =>
                string.Equals(x, y, StringComparison.OrdinalIgnoreCase),
            c => c.ToLower().GetHashCode()));
        void initExclude(HttpApplication context)
        {
            foreach (var p in "~/Content|~/Scripts|~/Html".Split('|'))
                resourceExtensions.Add(p.ToLower());
        }
        void OnEndRequest(object sender, System.EventArgs e)
        {
            var currentpath = HttpContext.Current.Request.PhysicalPath;
            if (!resourceExtensions.Any(x =>
                currentpath.StartsWith(HttpContext.Current.Server.MapPath(x), StringComparison.OrdinalIgnoreCase)))
            {
                var handler = new DebugHttpHandler();
                handler.ProcessRequest(HttpContext.Current);
            }
        }

        public void Dispose()
        {
        }
    }
}
